package com.drill.controller.folder;

import java.util.List;

import com.drill.controller.system.log.SysLog;
import com.jfinal.log.Log;
import com.jflyfox.jfinal.base.BaseService;
import com.jflyfox.util.StrUtils;
import com.jflyfox.util.cache.Cache;
import com.jflyfox.util.cache.CacheManager;

/**
* @auto ket
* @date 2016年6月27日 下午5:21:54
*/

public class FolderService extends BaseService {
	
	private final static Log log = Log.getLog(SysLog.class);
	
	private final static String cacheName = "FolderService";
	
	/**
	 * 目录缓存
	 */
	private static Cache cache = CacheManager.get(cacheName);
	
	private final static String urlkeyCacheName = "JFlyFoxUtils";
	private static Cache urlkeyCache = CacheManager.get(urlkeyCacheName);

	/**
	 * 更新缓存
	* @auto ket
	* @date 2016年6月27日 下午5:25:02
	* @param
	* @return
	 */
	public void updateCache() {
		cache.clear();

		// 初始化urlKey
		initMenuKey();
	}
	
	public static void initMenuKey() {
		log.info("####目录Key初始化......");
		urlkeyCache.clear();
		List<Folder> folders = Folder.dao.findByWhere(" where status = 1 order by sort");
		for (Folder tbFolder : folders) {
			if (StrUtils.isNotEmpty(tbFolder.getKey())) {
				urlkeyCache.add(tbFolder.getKey(), tbFolder.getId() + "");
				urlkeyCache.add(tbFolder.getId() + "", tbFolder.getKey());
			}
		}
	}
	
	public static String getMenu(String key) {
		return (urlkeyCache.get(key) == null) ? key : urlkeyCache.get(key).toString();
	}
	
	public Folder getFolder(int folderId) {
		Folder folder = Folder.dao.findFirstCache(cacheName, "getFolder_" + folderId //
		, "select * from tb_folder where id = ? ", folderId);
		return folder;
	}
	
	public String getSelect(Integer selected){
		List<Folder> folders = Folder.dao.findByWhere(" where status = 1 order by sort");
		StringBuffer sb = new StringBuffer("");
		if (folders != null && folders.size() > 0) {
			for (Folder folder : folders) {
				sb.append("<option value=\"");
				sb.append(folder.getInt("id"));
				sb.append("\" ");
				sb.append((selected != null && folder.getInt("id").intValue() == selected) ? "selected" : "");
				sb.append(">");
				sb.append(folder.getStr("name"));
				sb.append("</option>");
			}
		}
		return sb.toString();
	}
	
	public List<Folder> getMenus(){
		List<Folder> folders=cache.get("getFolder_menus");
		if(folders==null){
			folders=Folder.dao.findByWhere(" where status = 1 and site_id=2 order by sort");
			cache.add("getFolder_menus", folders);
		}
		
		log.info(folders.toString());
		return folders;
	}

}
